package com.ruoyi.drinkwater.service.impl;

import com.ruoyi.base.domain.BussinessItemVo;
import com.ruoyi.base.mapper.PublicToolsMapper;
import com.ruoyi.base.service.PublicToolsService;
import com.ruoyi.common.utils.BankerSRoundingUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ListDataUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.drinkwater.mapper.BusWaterDrinkSourceManualMapper;
import com.ruoyi.drinkwater.service.IBusWaterDrinkSourceManualService;
import com.ruoyi.utli.SegmentFormula;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: yanakai@126.com
 * @CreateDate: 2025-09-25 00:30
 * @UpdateUser: yanakai@126.com
 * @UpdateDate: 2025-09-25 00:30
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Service
public class BusWaterDrinkSourceManualServiceImpl implements IBusWaterDrinkSourceManualService {

    @Resource
    private BusWaterDrinkSourceManualMapper busWaterDrinkSourceManualMapper;

    @Autowired
    private PublicToolsService publicToolsService;

    @Autowired
    private PublicToolsMapper publicToolsMapper;

    @Autowired
    private SegmentFormula segmentFormula;

    @Override
    public List<Map<String, Object>> getManualWaterLastTime(Map<String, Object> params) {
        return busWaterDrinkSourceManualMapper.getManualWaterLastTime(params);
    }

    @Override
    public List<Map<String, Object>> getManualWaterDataList(Map<String, Object> params) {
        List<Map<String, Object>> resultList=new ArrayList<>();
        if (StringUtils.isEmpty(params.get("beginTime")!=null  ? params.get("beginTime").toString() : "") || StringUtils.isEmpty(params.get("endTime")!=null ? params.get("endTime").toString() : "")){
            params.put("beginTime", DateUtils.getFirstDayOfMonth(DateUtils.getNowDate()));
            params.put("endTime", DateUtils.getLastDayOfMonth(DateUtils.getNowDate()));
        }else {
            params.put("beginTime", DateUtils.getFirstDayOfMonth(DateUtils.parseDate(params.get("beginTime").toString())));
            params.put("endTime", DateUtils.getLastDayOfMonth(DateUtils.parseDate(params.get("endTime").toString())));
        }
        List<Map<String, Object>> mapList = busWaterDrinkSourceManualMapper.getManualWaterDataList(params);
        if(StringUtils.isNotEmpty(mapList)){
            BussinessItemVo vo = new BussinessItemVo();
            vo.setBussinessCategoryCode(params.get("businessCategoryCode").toString());
            // 对数组进行分组，根据时间进行分组
            Map<String, List<Map<String, Object>>> groupedTimeMap = mapList.stream().collect(
                    Collectors.groupingBy(map -> (String)map.get("sampleDate"))
            );
            // 将分组后的数据转换为结果列表,将色度、嗅和味、浑浊度、肉眼可见物；做行转列处理；
            groupedTimeMap.forEach((sampleDate, dataList) -> {
                // 对dataList进行分组，根据segmentId进行分组
                Map<String, List<Map<String, Object>>> groupedSegmentMap = dataList.stream().collect(
                        Collectors.groupingBy(map -> (String)map.get("segmentId"))
                );
                // 将分组后的数据转换为结果列表
                groupedSegmentMap.forEach((segmentId, segmentDataList) -> {
                    Map<String, Object> segmentResultMap = new HashMap<>();
                    segmentResultMap.put("segmentId", segmentId); // 断面id
                    segmentResultMap.put("segmentName", segmentDataList.get(0).get("segmentName")); // 断面名称
                    segmentResultMap.put("sampleDate", sampleDate); // 采样时间
                    segmentResultMap.put("businessCategoryCode", segmentDataList.get(0).get("businessCategoryCode")); // 业务类别代码
                    segmentResultMap.put("businessCategory", segmentDataList.get(0).get("businessCategory")); // 业务类别名称
                    segmentResultMap.put("qualityLevel", segmentDataList.get(0).get("qualityLevel"));// 水质等级
                    segmentResultMap.put("qualityLevelName", segmentDataList.get(0).get("qualityLevelName")); // 水质等级描述
                    segmentResultMap.put("evaluationTrendCode", segmentDataList.get(0).get("evaluationTrendCode")); // 水质评价
                    segmentResultMap.put("evaluationTrend", segmentDataList.get(0).get("evaluationTrend")); // 水质趋势评价结果
                    segmentResultMap.put("waterQuality", segmentDataList.get(0).get("waterQuality")); // 水质质量等级
                    segmentResultMap.put("isOversStandard", segmentDataList.get(0).get("isOversStandard")); // 是否超标
                    segmentResultMap.put("overStandardDescribe", segmentDataList.get(0).get("overStandardDescribe")); // 超标描述
                    segmentDataList.forEach(data -> {
                        Object effectiveValue = data.get("effectiveValue");
                        // 只有当effectiveValue不为空且大于0时才添加到结果中
                        if (effectiveValue != null &&
                                (effectiveValue instanceof Number && ((Number) effectiveValue).doubleValue() > 0)) {
                            // 去除小数点后多余的0
                            DecimalFormat decimalFormat = new DecimalFormat("####.####");
                            segmentResultMap.put(data.get("itemCode")+"_value", decimalFormat.format(effectiveValue));
                        }
                    });
                    resultList.add(segmentResultMap);
                });
            });

        }
        return resultList;
    }

    @Override
    public List<Map<String, Object>> isManualWqDataBasicsmonitordata(Map maps) {
        List<Map<String, Object>> listdata = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#.0000");
        DecimalFormat dfql = new DecimalFormat("###.###");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Object yearYOY = maps.get("yearYOY");//同比年 如果空就不展示同比 根据传入的数据展示几年数据
        Object beginTime =null;
        if(yearYOY!=null&&!"".equals(yearYOY)){
            Integer yearinteger = Integer.valueOf(String.valueOf(yearYOY));//年份
            Object beginTimeks = maps.get("beginTime");//开始时间
            if(beginTimeks!=null&&!"".equals(beginTimeks)){

                String dataTImes = String.valueOf(beginTimeks);
                Date parse = null;
                try {
                    parse = format.parse(dataTImes);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(parse);
                calendar.add(Calendar.YEAR, -yearinteger);
                Date time = calendar.getTime();
                beginTime = format.format(time);
            }

        }else {
            beginTime= maps.get("beginTime");//开始时间
        }
        // maps.put("beginTime",beginTime);
        Object endTime = maps.get("endTime");//结束时间
        //查询出监测时间
        List<Map<String, Object>> manualList = busWaterDrinkSourceManualMapper.isManualWqDataBasicsmonitordataTime(maps);
        //查询监测值数据
        List<Map<String, Object>> manualListData = busWaterDrinkSourceManualMapper.isManualWqDataBasicsmonitordata(maps);
        //查询标准值
        Map<String, Object> wqBasStandardcategorymap = new HashMap<>();

        if("CBF1".equals(String.valueOf(maps.get("prop")))){
            wqBasStandardcategorymap.put("type", "1");
        }else{
            wqBasStandardcategorymap.put("type", "3");

        }

        List<Map<String, Object>> wqBasStandardcategorylist = publicToolsMapper.wqBasStandardcategorylist(wqBasStandardcategorymap);

        BussinessItemVo itemVo = new BussinessItemVo();
        itemVo.setBussinessCategoryCode(String.valueOf(maps.get("prop")));
        List<Map<String, Object>> itemList = publicToolsService.bussinessItemData(itemVo);

        //源对象条件判断属性名 断面id
        String srcEqualProp = "SegmentID";
        //源对象待设置属性名   断面时间
        String srcSetProp = "SampleDatesdb";
        String dataSource = "dataSource";

        /*因子id加 _Val 是监测因子数据
        因子id加 _OverTimes 是超标倍数
        因子id加 _IsOver 是否超标 0正常 1超标*/
        long t1 = System.currentTimeMillis();
        //使用Java8自带的stream特性进行转换行转列

        List<Map<String, Object>> resultList = manualList.stream().map(m1 -> {
            //超标描述
            List<Map<String, Object>> overStandardFactors = new ArrayList<>();
            String overMessage = "";
            manualListData.stream()  //获取监测值的数据
                    .filter(m2 -> Objects.equals(m2.get(srcEqualProp), m1.get(srcEqualProp)) && Objects.equals(m2.get(srcSetProp), m1.get(srcSetProp)) && Objects.equals(m2.get(dataSource), m1.get(dataSource)))
                    .forEach(m2 -> {
                        //分组
                        Object itemCode = m2.get("ItemCode");
                        Object itemName = m2.get("ItemName");
                        Object TargetLevel = m2.get("TargetLevel");
                        Object Unit = m2.get("Unit");
                        Object SegmentCategory = m2.get("SegmentCategory");
                        List<Map<String, Object>> sunmapsWaterTypelist = new ArrayList<>();
                        if (wqBasStandardcategorylist != null && wqBasStandardcategorylist.size() > 0) {
                            //使用Java8自带的stream特性进行转换行转列
                            // 使用filter()方法根据条件过滤元素
                            sunmapsWaterTypelist = wqBasStandardcategorylist.stream()
                                    .filter(wqBasStandardcategorylistmap -> String.valueOf(wqBasStandardcategorylistmap.get("ItemCode")).equals(String.valueOf(itemCode)) && String.valueOf(wqBasStandardcategorylistmap.get("Level")).equals(String.valueOf(TargetLevel)) && String.valueOf(wqBasStandardcategorylistmap.get("WaterType")).equals(String.valueOf(SegmentCategory)))   // 只保留能被2整除的元素
                                    .collect(Collectors.toList());
                        }
                        List<Map<String, Object>> itemEvaluteList = itemList.stream().filter(s-> String.valueOf(s.get("itemCode")).equals(String.valueOf(itemCode))).collect(Collectors.toList());
                        int ieke=3;
                        if (sunmapsWaterTypelist != null && sunmapsWaterTypelist.size() > 0) {
                            Object standardValue = sunmapsWaterTypelist.get(0).get("StandardValue");
                            m1.put(m2.get("ItemCode") + "_standardValue", standardValue);//监测因子对应值
                            if(standardValue!=null&&!"".equals(standardValue)){
                                String valueAsString = String.valueOf(standardValue);
                                if (valueAsString.indexOf('.') < 0) {
                                    // 没有小数点，即整数或零小数位
                                    //return 0;
                                }

                                ieke=valueAsString.length() - valueAsString.indexOf('.');
                            }
                        }

                        if("15DE941F-A221-4D9C-8387-48B0E99F6E25".equals(String.valueOf(m2.get("ItemCode")).toUpperCase())){
                            m1.put(m2.get("ItemCode") + "_standardValue", 6 +"~"+ 9);//监测因子对应值
                        }
                        Object keepPointBits = m2.get("KeepPointBits");
                        if(keepPointBits!=null&&!"".equals(keepPointBits)){
                            ieke=Integer.valueOf(String.valueOf(keepPointBits));
                        }
                        Object effectiveValue = m2.get("EffectiveValue");
                        if(effectiveValue!=null&&!"".equals(effectiveValue)&&Double.valueOf(String.valueOf(effectiveValue))>0){
                            Double aDouble = Double.valueOf(String.valueOf(effectiveValue));
                            String data = BankerSRoundingUtils.sciCal(aDouble, ieke);
                            if(data!=null&&!"".equals(data)&&Double.valueOf(data)>0){
                                m1.put(m2.get("ItemCode") + "_Val", data);//监测因子对应值
                            }else {
                                Double aDouble1 = segmentFormula.ConvertData(aDouble);
                                m1.put(m2.get("ItemCode") + "_Val", aDouble1);//监测因子对应值
                            }

                            m1.put(m2.get("ItemCode") + "_OrginalValue", m2.get("OrginalValue"));//监测因子对应值
                        }else {
                            m1.put(m2.get("ItemCode") + "_Val",-1);//监测因子对应值
                            m1.put(m2.get("ItemCode") + "_OrginalValue",-1);//监测因子对应值
                        }

                        m1.put(m2.get("ItemCode") + "_IsOver", m2.get("IsOver"));//监测参数是否超标
                        m1.put(m2.get("ItemCode") + "_OverTimes", m2.get("OverTimes"));//监测值超标倍数
                        m1.put("SegmentID", m2.get("SegmentID"));//断面id
                        Object qualityLevelName = m2.get("QualityLevel");
                        if (qualityLevelName!=null&&!"".equals(qualityLevelName)&&Integer.valueOf(String.valueOf(qualityLevelName))>0) {
                            m1.put("IsOvers", m2.get("IsOvers"));//断面id
                        } else {
                            m1.put("IsOvers", "");//断面id
                        }

                        m1.put("SegmentName", m2.get("SegmentName"));//断面名称

                        m1.put("id",m2.get("SegmentID"));
                        m1.put("siteType", "IsManual");
                        m1.put("segmentCategory", SegmentCategory);
                        m1.put("IsDrink", m2.get("IsDrink"));
                        m1.put("segmentName", m2.get("SegmentName"));
                        m1.put("dataSource", m2.get("dataSource"));
                        m1.put("QualityLevel", m2.get("QualityLevel"));//断面水质级别
                        m1.put("Level", m2.get("QualityLevelName"));//断面水质级别
                        m1.put("TargetLevel", m2.get("TargetLevelName"));//断面目标级别
                        m1.put("PollutionItem", m2.get("PollutionItem"));//断面超标描述
                        Object sampleDate = m2.get("SampleDate");
                        Object SampleDatemonday = m2.get("SampleDatemonday");
                        Object SampleDatesdb = m2.get("SampleDatesdb");
                        if(SampleDatemonday!=null&&!"".equals(SampleDatemonday)&&"12-31".equals(SampleDatemonday)){
                            m1.put("SampleDate","全分析");//监测时间
                            m1.put("SampleDatesdb",SampleDatesdb);//监测时间
                        }else {
                            m1.put("SampleDate",sampleDate);//监测时间
                            m1.put("SampleDatesdb",SampleDatesdb);//监测时间
                        }

                        m1.put("moonSampleDate", m2.get("moonSampleDate"));//监测时间
                        m1.put("yeraSampleDate", m2.get("yeraSampleDate"));//监测时间
                        m1.put("RiverName", m2.get("RiverName"));//河流名称
                        m1.put("RiverID", m2.get("RiverID"));//河流id
                        m1.put("type", "当期");//监测时间
                        m1.put("longitude", m2.get("longitude"));//经度
                        m1.put("latitude", m2.get("latitude"));//纬度

                        //是否超标
                        if(StringUtils.isNotEmpty(itemEvaluteList) && itemEvaluteList.size() > 0){
                            String isEvalute=String.valueOf(itemEvaluteList.get(0).get("isEvalute"));
                            if("1".equals(isEvalute)){
                                String isoverstandard= String.valueOf(m2.get("IsOver"));
//                           BigDecimal effectivevalue= hourdata.getEffectivevalue();
                                String overstandardtimes=String.valueOf(m2.get("OverTimes"));
                                if("1".equals(isoverstandard)){
                                    Map<String, Object> overMap=new HashMap<>();
                                    overMap.put("itemName", itemName);
                                    overMap.put("value", dfql.format(effectiveValue));
                                    if(StringUtils.isNotEmpty(overstandardtimes) && !"null".equals(overstandardtimes) && !"--".equals(overstandardtimes)){
                                        overMap.put("overstandardtimes", overstandardtimes);
                                    }else{
                                        overMap.put("overstandardtimes", "");
                                    }
                                    Object standardValue="";
                                    if("15DE941F-A221-4D9C-8387-48B0E99F6E25".equals(String.valueOf(m2.get("ItemCode")).toUpperCase())){
                                        standardValue="6~9";//监测因子对应值

                                    }else{
                                        if(StringUtils.isNotEmpty(sunmapsWaterTypelist) && sunmapsWaterTypelist.size()>0)    {
                                            standardValue = sunmapsWaterTypelist.get(0).get("StandardValue");
                                        }
                                    }
                                    overMap.put("standardValue", standardValue);
                                    overMap.put("unit", Unit);

                                    overStandardFactors.add(overMap);
                                }
                            }
                        }

                        Object assessType = m2.get("AssessTypeCode");
                        Object targetLevel = m2.get("PollutionItem");
                        //  Object qualityLevelName = m2.get("QualityLevel");
                        if (!"无类别".equals(qualityLevelName)&&qualityLevelName!=null&&!"".equals(qualityLevelName)&&Integer.valueOf(String.valueOf(qualityLevelName))>0&&targetLevel != null && !"".equals(targetLevel)) {
                            m1.put("SegmentIsOver", "超标");//监测时间
                        } else if (!"无类别".equals(qualityLevelName)&&qualityLevelName!=null&&!"".equals(qualityLevelName)&&Integer.valueOf(String.valueOf(qualityLevelName))>0){
                            m1.put("SegmentIsOver", "达标");//监测时间
                        }else {
                            m1.put("SegmentIsOver", "");//监测时间
                        }
                        //水质评价
                        m1.put("waterQuality", m2.get("waterQuality"));
                        //水质指数
                        Object segmentIndex = m2.get("segmentIndex");
                        if(segmentIndex!=null&&!"".equals(segmentIndex)&&Double.valueOf(String.valueOf(segmentIndex))>0){
                            m1.put("segmentIndex",df.format(segmentIndex));
                        }

                        //水质趋势
                        m1.put("evaluationTrendCode", m2.get("evaluationTrendCode"));
                        m1.put("evaluationTrend", m2.get("evaluationTrend"));



                        String min = "";
                        if (assessType != null && !"".equals(assessType)) {
                            String[] split = String.valueOf(assessType).split(",");
                            min = split[0];
                            for (int i = 1; i < split.length; i++) {
                                if (Integer.parseInt(min) < Integer.parseInt(split[i])) { //最大/最小 根据需求更改 大于号或小于号 即可
                                    min = split[i];
                                }
                            }
                        }
                        if (min != null && !"".equals(min)) {
                            if (min.equals("0")) {
                                m1.put("AssessType", "国考");//考核类型编码(0 国考 1省考 2市考)
                            }
                            if (min.equals("1")) {
                                m1.put("AssessType", "省考");//考核类型编码(0 国考 1省考 2市考)
                            }
                            if (min.equals("2")) {
                                m1.put("AssessType", "市考");//考核类型编码(0 国考 1省考 2市考)
                            }
                        } else {
                            m1.put("AssessType", "");
                        }

                        m1.put("ControlLevel", m2.get("ControlLevel"));//控制级别（国控/省控/市控）
                        m2.clear();
                    });
            if(StringUtils.isNotEmpty(overStandardFactors)&&overStandardFactors.size()>0){
                for(Map<String,Object> retMap:overStandardFactors){
                    Object itemName= retMap.get("itemName");
                    Object value= retMap.get("value");
                    Object standardValue= retMap.get("standardValue");
                    Object unit= retMap.get("unit");

//                   Object overstandardtimes= retMap.get("overstandardtimes");
                    overMessage=overMessage+itemName+"(监测值："+value+unit;
//                    if(StringUtils.isNotNull(overstandardtimes) && !"".equals(overstandardtimes) && !"null".equals(overstandardtimes) && !"--".equals(overstandardtimes)){
//                        overMessage=overMessage+",倍数："+overstandardtimes;
//                    }
                    if(StringUtils.isNotNull(standardValue) && !"".equals(standardValue) && !"null".equals(standardValue) && !"--".equals(standardValue)){
                        overMessage=overMessage+",标准值："+standardValue+unit;
                    }
                    overMessage=overMessage+")、";
                }
            }
            if(StringUtils.isNotEmpty(overMessage)){
                m1.put("PollutionItem",overMessage.substring(0,overMessage.length()-1));
            }else{
                m1.put("PollutionItem","");
            }
            return m1;
        }).collect(Collectors.toList());
        //   System.out.println(System.currentTimeMillis() - t1);
        if (resultList != null && resultList.size() > 0) {
            for (Map<String, Object> data : resultList) {
                Object segmentName = data.get("SegmentName");
                if (segmentName != null && !"".equals(segmentName)) {
                    listdata.add(data);
                }
            }
        }
        List<Map<String, Object>> segmentName = new ArrayList<>();
        if (listdata != null && listdata.size() > 0) {
            segmentName = ListDataUtil.twoObjectascendingOrder(listdata, "SegmentName", "SampleDate");

        }

        return segmentName;
    }

}
